import {sectionsData} from "../constants/sectionsData";
import {call, Loading, Module, register, SagaGenerator} from "../core-native";
import OrderPage from "../pages/OrderPage";
import {RootState} from "../types";
import {dishItemI} from "../types/OrderState";
import {produce} from "immer";
// @ts-ignore
import RCTNativeAppEventEmitter from "react-native/Libraries/EventEmitter/RCTNativeAppEventEmitter";
import {EMIT_ORDER_NOW} from "../constants/emits";
import {LOADING_ORDER} from "../constants/loadingKey";

class OrderModule extends Module<RootState, "order"> {
    *onEnter(routeParameters: object): SagaGenerator {
        console.log("进入之前", routeParameters);
    }
    *addDish(item: dishItemI) {
        let orderMap = this.state.orderMap;
        orderMap = produce(orderMap, draft => {
            if (draft["id" + item.id]) {
                draft["id" + item.id].num++;
            } else {
                draft["id" + item.id] = produce(item, draft2 => {
                    draft2.num = 1;
                });
            }
        });
        this.setState({orderMap});
    }
    *deleteDish(item: dishItemI) {
        let orderMap = this.state.orderMap;
        orderMap = produce(orderMap, draft => {
            if (draft["id" + item.id].num > 1) {
                draft["id" + item.id].num--;
            } else {
                delete draft["id" + item.id];
            }
        });
        this.setState({orderMap});
    }

    @Loading(LOADING_ORDER)
    *orderNow() {
        const res: any = yield* call(
            () =>
                new Promise(resolve => {
                    setTimeout(() => {
                        resolve({succeed: true});
                    }, 1000);
                })
        );
        if (res.succeed) {
            this.setState({orderMap: {}});
            RCTNativeAppEventEmitter.emit(EMIT_ORDER_NOW);
        }
    }
}

const initState: RootState["app"]["order"] = {
    orderMap: {},
    sectionsData: sectionsData,
};

const module = register(new OrderModule("order", initState));
export const OrderActions = module.getActions();
export const Order = module.attachLifecycle(OrderPage);
